//
//  linklistQueue.swift
//  SetAndMap
//
//  Created by lhc on 2024/6/22.
//

import Foundation

class LinkListQueue<E: Equatable> {
    
    private var size = 0
    private var head: LinkListNode<E>?
    private var tail: LinkListNode<E>?
    
    /// 获取链表队列size
    func getSize() -> Int {
        return self.size
    }
    
    /// 判断链表队列是否为空
    func isEmpty() -> Bool {
        return self.size == 0
    }
    
    /// 入队
    func enqueue(e: E) {
        
        let node = LinkListNode<E>(e: e)
        
        if self.isEmpty() {
            // 如果是空队列 self.tail = self.head = node
            self.head = node
            self.tail = node
        }else {
            // 否则在尾部加上新node
            self.tail?.next = node
            self.tail = node
        }
        
        self.size += 1
    }
    
    /// 出队
    func dequeue() -> E? {
        guard !self.isEmpty() else { return nil }
        
        guard let head = self.head else { return nil }
        
        if self.size == 1 {
            self.head = nil
            self.tail = nil
        }else {
            // 把self.head往后移动到head的next
            self.head = head.next
            head.next = nil
        }
        
        self.size -= 1
        return head.e
    }
}
